package com.ruoyi.business.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.business.domain.bo.TCourseResourceBo;
import com.ruoyi.business.domain.vo.TCourseResourceVo;
import com.ruoyi.business.enumeration.ResourceStatusEnum;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysOssService;
import com.ruoyi.system.service.ISysRoleService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.TCourseResource;
import com.ruoyi.business.service.ITCourseResourceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * CourseResourceController
 * 
 * @author 最爱喝兽奶
 * @date 2024-03-20
 */
@RestController
@RequestMapping("/business/CourseResource")
public class TCourseResourceController extends BaseController
{
    @Autowired
    private ITCourseResourceService tCourseResourceService;

    @Autowired
    private ISysOssService ossService;

    @Autowired
    private ISysRoleService roleService;


    /**
     * 查询CourseResource列表
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:list')")
    @GetMapping("/list")
    public TableDataInfo list(TCourseResourceBo tCourseResource)
    {
        startPage();
        List<TCourseResourceVo> list = tCourseResourceService.selectTCourseResourceList(tCourseResource);
        return getDataTable(list);
    }

    /**
     * 导出CourseResource列表
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:export')")
    @Log(title = "CourseResource", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TCourseResourceBo tCourseResource)
    {
        List<TCourseResourceVo> list = tCourseResourceService.selectTCourseResourceList(tCourseResource);
        ExcelUtil<TCourseResourceVo> util = new ExcelUtil<TCourseResourceVo>(TCourseResourceVo.class);
        util.exportExcel(response, list, "CourseResource数据");
    }

    /**
     * 获取CourseResource详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tCourseResourceService.selectTCourseResourceById(id));
    }

    /**
     * 新增CourseResource
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:add')")
    @Log(title = "CourseResource", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCourseResource tCourseResource)
    {
        return toAjax(tCourseResourceService.insertTCourseResource(tCourseResource));
    }

    /**
     * 修改CourseResource
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:edit')")
    @Log(title = "CourseResource", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TCourseResource tCourseResource)
    {
        return toAjax(tCourseResourceService.updateTCourseResource(tCourseResource));
    }

    /**
     * 审核通过
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:reviewSuccessed')")
    @Log(title = "CourseResource", businessType = BusinessType.UPDATE)
    @PutMapping("/reviewSuccessed/{id}")
    public AjaxResult reviewSuccessed(@PathVariable("id") Long id)
    {
        TCourseResource newCourseResource = new TCourseResource();
        newCourseResource.setId(id);
        newCourseResource.setStatus(ResourceStatusEnum.REVIEW_SUCCESSED.getValue());
        return toAjax(tCourseResourceService.updateTCourseResource(newCourseResource));
    }

    /**
     * 审核失败
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:reviewFailed')")
    @Log(title = "CourseResource", businessType = BusinessType.UPDATE)
    @PutMapping("/reviewFailed/{id}")
    public AjaxResult reviewFailed(@PathVariable("id") Long id)
    {
        TCourseResource newCourseResource = new TCourseResource();
        newCourseResource.setId(id);
        newCourseResource.setStatus(ResourceStatusEnum.REVIEW_FAILED.getValue());
        return toAjax(tCourseResourceService.updateTCourseResource(newCourseResource));
    }

    /**
     * 删除CourseResource
     */
    @PreAuthorize("@ss.hasPermi('business:CourseResource:remove')")
    @Log(title = "CourseResource", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tCourseResourceService.deleteTCourseResourceByIds(ids));
    }

    @ApiOperation("下载资源文件")
    @GetMapping("/download/{id}")
    public void downloadTemplateFile(@PathVariable("id") Long id,
                                     HttpServletResponse response) throws IOException {
        // 先判断是否为管理员
        String userId = null;
        try {
            userId = getUserId();
        }catch (Exception e) {
            logger.info("未登录用户访问");
        }
        byte[] data = null;
        TCourseResource courseResource = null;
        if (SecurityUtils.isAdmin(userId)) {
            courseResource = tCourseResourceService.getById(id);
            if (null != courseResource) {
                data = ossService.download(String.valueOf(courseResource.getOssId()));
                tCourseResourceService.addDownloadNum(id);
            }else {
                response.getWriter().println("资源信息错误, 请检查资源id");
                return;
            }
        }else {
            // 如果是老师可以下载
            List<SysRole> sysRoles = null;
            if (userId == null) {
                sysRoles = new ArrayList<>();
            }else {
                sysRoles = roleService.selectRolesByUserId(userId);
            }
            if (isTeacher(sysRoles)) {
                courseResource = tCourseResourceService.getById(id);
                if (null != courseResource) {
                    data = ossService.download(String.valueOf(courseResource.getOssId()));
                    tCourseResourceService.addDownloadNum(id);
                }else {
                    response.getWriter().println("资源信息错误, 请检查资源id");
                    return;
                }
            }else {
                courseResource = tCourseResourceService.getById(id);
                if (null != courseResource) {
                    if (ResourceStatusEnum.REVIEW_SUCCESSED.getValue().equals(courseResource.getStatus())) {
                        data = ossService.download(String.valueOf(courseResource.getOssId()));
                        tCourseResourceService.addDownloadNum(id);
                    }else {
                        response.getWriter().println("资源为审核通过，无法下载");
                        return;
                    }
                }else {
                    response.getWriter().println("资源信息错误, 请检查资源id");
                    return;
                }
            }
        }
        genCode(response, data, courseResource.getFullSourceName());
    }

    private boolean isTeacher(List<SysRole> sysRoles) {
        for (SysRole sysRole : sysRoles) {
            if ("teacher".equals(sysRole.getRoleName())) {
                return true;
            }
        }
        return false;
    }

    @GetMapping("/share/{id}")
    public AjaxResult shareResource(@PathVariable("id") String id,
                                    HttpServletRequest request) {
        AjaxResult result = null;
        if (null != id) {
            TCourseResource courseResource = tCourseResourceService.getById(id);
            if (courseResource.getStatus().equals(ResourceStatusEnum.REVIEW_SUCCESSED.getValue())) {
                result = AjaxResult.success();
                String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                baseUrl = baseUrl + "/business/CourseResource/download/" + id;
                result.put(AjaxResult.DATA_TAG, baseUrl);
            }else {
                result = AjaxResult.error("资源未审核通过");
            }
        }else {
            result = AjaxResult.error("请检查传入id");
        }
        return result;
    }


    /**
     * 生成文件
     */
    private void genCode(HttpServletResponse response, byte[] data, String filename) throws IOException
    {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));
        response.setContentType("application/octet-stream;charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
